<template>
  <div class="main_box">
    <div class="add_wrap">
      <div class="tit">
        <h2>项目信息</h2>
        <el-button plain size="small" type="success" icon="fa fa-mail-forward" @click="returnList"> 返 回</el-button>
      </div>
      <el-form :model="reportForm" ref="reportForm" label-width="160px" :rules="roleRules" class="el-form-three">
        <el-row>
          <el-form-item label="医院名称" prop="hospitalId">
            <el-select v-model="reportForm.hospitalId" filterable clearable reserve-keyword :loading="loadingIns" placeholder="请选择医院" @change="hospitalChange">
              <el-option v-for="item in pickHospitalList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="医院科室" prop="officeId" class="suffix-operation__wrapper">
            <el-select v-model="reportForm.officeId" filterable clearable reserve-keyword :loading="loadingIns" placeholder="请选择科室" @change="officeChange">
              <el-option v-for="item in pickOfficeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button class="suffix-operation" plain circle type="warning" icon="el-icon-plus" @click.stop="addOffice"></el-button>
            <!-- <a
              href="javascript:void(0);"
              @click="addOffice"
              style="margin-left: 230px"
              >快速创建</a> -->
          </el-form-item>

          <el-form-item label="医生名称" prop="doctorId" class="suffix-operation__wrapper">
            <el-select v-model="reportForm.doctorId" filterable clearable reserve-keyword :loading="loadingIns" placeholder="请选择医生">
              <el-option v-for="item in pickDoctorList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button class="suffix-operation" plain circle type="warning" icon="el-icon-plus" @click="addDoctor"></el-button>
            <!-- <a
              href="javascript:void(0);"
              @click="addDoctor"
              style="margin-left: 230px"
              >快速创建</a
            > -->
          </el-form-item>

          <el-form-item label="医院项目" prop="hospitalItemIdList" class="suffix-operation__wrapper">
            <el-select
              v-model="reportForm.hospitalItemIdList"
              filterable
              clearable
              multiple
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医院项目"
              @change="hospitalItemChange"
            >
              <el-option v-for="item in pickHospitalItemList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button class="suffix-operation" plain circle type="warning" icon="el-icon-plus" @click="$router.push('/item/hospitalItemAdd')"></el-button>
          </el-form-item>
          <!-- <el-form-item label="医检项目" prop="itemNames" v-if="!itemDisabled">
            <el-select
              v-model="reportForm.insItemIdList"
              filterable
              multiple
              placeholder="请选择医检项目"
              @change="itemListChange"
            >
              <el-option
                v-for="item in itemNameList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item label="项目名称" prop="itemName">
            <el-input v-model.trim="reportForm.itemName" :disabled="reportForm.hospitalItemIdList && reportForm.hospitalItemIdList.length ? true : false"></el-input>
          </el-form-item>

          <div v-if="userRole === 1">
            <el-form-item label="医检名称" prop="institutionId">
              <el-select
                v-model="reportForm.institutionId"
                filterable
                clearable
                reserve-keyword
                :loading="loadingIns"
                placeholder="请选择医检机构"
                @focus="listInstitution"
                @change="institutionChange"
              >
                <el-option v-for="item in pickInstitutionList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="医检科室" prop="insOfficeId">
              <el-select v-model="reportForm.insOfficeId" filterable clearable reserve-keyword placeholder="请选择科室">
                <el-option v-for="item in pickInsOfficeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-table :data="itemContentList" style="width: fit-content; margin: 0 0 10px 94px">
              <el-table-column prop="itemName" label="项目名称" width="150" align="center"> </el-table-column>
              <el-table-column prop="itemCode" label="编号" width="150" align="center"> </el-table-column>
              <el-table-column prop="itemPrice" label="项目原价" width="150" align="center"> </el-table-column>
              <el-table-column prop="itemSalePrice" label="项目合作价" width="150" align="center"> </el-table-column>
              <el-table-column label="样本" width="300" align="center">
                <template slot-scope="{ row }">
                  <el-select v-model="row.sampleId">
                    <el-option v-for="item in pickSampleTypeList" :value="item.value" :label="item.label" :key="item.value"></el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-row>

        <div class="tit">
          <h2>基础信息</h2>
        </div>
        <el-row>
          <el-form-item v-if="false" label="查询号" prop="searchCode">
            <el-input v-model.trim="reportForm.searchCode"></el-input>
          </el-form-item>

          <el-form-item label="医检条码号" prop="insReportCode">
            <el-input v-model.trim="reportForm.insReportCode" @blur="checkInsCodeIsExist"> </el-input>
            <br /><span id="insCodeHides" :hidden="insCodeHide" style="color: red; font-size: xx-small"> <i class="el-icon-warning" />医检条码号重复！</span>
          </el-form-item>
          <el-form-item label="平台条码号" prop="myReportCode">
            <el-input v-model.trim="reportForm.myReportCode"></el-input>
          </el-form-item>

          <el-form-item label="送检时间" prop="reportBeginTime">
            <el-date-picker
              v-model="reportForm.reportBeginTime"
              type="datetime"
              :picker-options="pickerBeginDateBefore"
              :default-value="timeDefaultShow"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="不填则默认为当前时间"
            ></el-date-picker>
            <div style="color: red" v-show="showTimeTip">所选时间为今天之前，请注意提交申请通过后再录入！</div>
          </el-form-item>
          <el-form-item label="报告状态" prop="reportState">
            <el-select v-model="reportForm.reportState" clearable reserve-keyword placeholder="请选择当前报告状态">
              <el-option v-for="item in pickCurReportStateList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="一级收样员" prop="syUserId">
            <el-select v-model="reportForm.syUserId" filterable clearable reserve-keyword placeholder="请选择一级收样员">
              <el-option v-for="item in pickSyUserList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="二级收样员" prop="syUserIdTwo">
            <el-select v-model="reportForm.syUserIdTwo" filterable clearable reserve-keyword placeholder="请选择二级收样员">
              <el-option v-for="item in pickSyUserList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button @click="addSubclass()" icon="el-icon-plus" plain round type="success" size="mini"></el-button>
          </el-form-item>
          <el-form-item prop="syUserIdList" v-for="(item, index) in reportForm.syUserIdList" :label="changSyUserLabel(index + 3)" :key="'syUserIdList' + index">
            <el-select v-model.lazy="item.userId" filterable clearable reserve-keyword placeholder="请选择收样员">
              <el-option v-for="item in pickSyUserList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <el-button @click="deleteSubclass(index)" icon="el-icon-close" plain round type="danger" size="mini"></el-button>
          </el-form-item>
          <!-- 5.21 liusixiang 次级收样员 -->
          <!--:label="(3+index)+'级收样员'"-->
          <!-- v-if="index == 0" --给添加符号设置限制条件 -->
          <el-form-item label="是否需要结果提醒" prop="isRemind">
            <el-switch v-model="reportForm.isRemind" active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="是否加急" prop="priority">
            <el-switch v-model="reportForm.priority" active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
          </el-form-item>
        </el-row>

        <div class="tit">
          <h2>患者信息</h2>
        </div>
        <el-row>
          <el-form-item label="患者姓名" prop="patientName">
            <el-input v-model.trim="reportForm.patientName"></el-input>
          </el-form-item>
          <el-form-item label="患者性别" prop="patientSex">
            <el-radio-group v-model="reportForm.patientSex">
              <el-radio :label="item.value" :key="item.value" v-for="item in sexLabels">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="患者身份证" prop="patientCard">
            <el-input v-model.trim="reportForm.patientCard" @change="cardChange"></el-input>
          </el-form-item>
          <el-form-item label="证件类型" prop="cardType">
            <el-radio-group v-model="reportForm.cardType">
              <el-radio :label="item.value" :key="item.value" @change="clickCardType(item.value)" v-for="item in IdCardLabels">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="患者出生日期">
            <el-date-picker v-model="reportForm.birthday" type="date" placeholder="选择出生日期" value-format="yyyy-MM-dd" @change="getAgeByBirthday(reportForm.birthday)">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="患者年龄">
            <el-input type="number" style="margin-bottom: 10px" v-model.trim="reportForm.patientAge"> <template slot="append">岁</template></el-input>
            <el-input type="number" style="margin-bottom: 10px" v-model.trim="reportForm.patientMonth"> <template slot="append">月</template></el-input>
            <el-input type="number" v-model.trim="reportForm.patientDay"> <template slot="append">天</template></el-input>
          </el-form-item>
          <el-form-item label="患者手机号" prop="patientPhone">
            <el-input type="number" v-model.trim="reportForm.patientPhone" @change="phoneChange"></el-input>
          </el-form-item>
          <el-form-item label="基本病情" prop="patientInfo">
            <el-input type="textarea" v-model.trim="reportForm.patientInfo"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model.trim="reportForm.remark"></el-input>
          </el-form-item>
        </el-row>

        <div class="tit">
          <h2>更多信息</h2>
        </div>

        <el-collapse>
          <el-collapse-item title="更多信息编辑器" name="1">
            <el-row>
              <RichEditor @getHtmlText="getHtmlText"></RichEditor>
            </el-row>
          </el-collapse-item>
        </el-collapse>

        <!--<div class="tit">
          <h2>上传报告单结果(仅适用于单个送检项目上传)</h2>
        </div>
        <el-row v-loading="loadingUpload" element-loading-text="文件上传中...">
        </el-row>-->

        <el-row>
          <el-form-item>
            <el-button type="primary" plain @click="sureReportClick" :disabled="disabledBtn">保 存</el-button>
            <el-button @click="returnList" :disabled="disabledBtn">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <el-dialog title="新增科室" :visible.sync="dialogOfficeFormVisible" :center="isCenter" width="500px">
      <el-form :model="addOfficeForm">
        <el-form-item label="科室名称：" label-width="150px">
          <el-input v-model="addOfficeForm.officeName" autocomplete="off" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item align="center">
          <el-button @click.native="dismissOffice">取 消</el-button>
          <el-button type="primary" @click.native="commitOffice">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="新增医生" :visible.sync="dialogDoctorFormVisible" :center="isCenter" width="500px">
      <el-form :model="addDoctorForm">
        <el-form-item label="医生姓名：" label-width="150px">
          <el-input v-model="addDoctorForm.doctorName" autocomplete="off" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="医生职称：" label-width="150px">
          <el-input v-model="addDoctorForm.doctorTitle" autocomplete="off" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item align="center">
          <el-button @click.native="dismissDoctor">取 消</el-button>
          <el-button type="primary" @click.native="commitDoctor">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 点击保存是否有同名提示的弹框 -->
    <el-dialog :title="dialogSameTipTitle" :visible.sync="dialogSameTipVisible">
      <div style="padding: 10px 20px">{{ dialogSameTipContent }}</div>
      <div slot="footer" style="text-align: center">
        <el-button @click="dialogSameTipVisible = false">取消</el-button>
        <el-button @click="continueConfirm(true)" type="primary">继续</el-button>
      </div>
    </el-dialog>
    <sameReportCheck ref="sameReportCheck" :dataList="sameReportList" @addReportSure="addReportSure"></sameReportCheck>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import SameReportCheck from '@/components/SameReportCheck';
import Map from '@/components/Map';
import RichEditor from '@/components/RichEditor';
import { mapGetters, mapActions } from 'vuex';
import AuthApi from '@/api/system/auth';
import ReportApi from '@/api/report/report';
import OfficeApi from '@/api/institution/office';
import HospitalApi from '@/api/institution/hospital';
import HospitalItemApi from '@/api/institution/hospitalItem';
import DoctorApi from '@/api/institution/doctor';
import InstitutionApi from '@/api/institution/institution';
import InstitutionItemApi from '@/api/institution/institutionItem';
import { getStorage } from '@/utils/auth';
import * as stn from '@/constants/storeName';

export default {
  data() {
    return {
      sexLabels: [
        { label: '男', value: 1 },
        { label: '女', value: 2 },
      ],
      IdCardLabels: [
        { label: '居民省份证', value: 1 },
        { label: '其他', value: 9 },
      ],
      pickCurReportStateList: [
        { label: '已收取', value: 5 },
        { label: '已送达', value: 10 },
      ],
      loadingIns: false,
      loadingCla: false,
      loadingUpload: false,
      // isForbidItemName:false,//是否禁用项目名称
      // itemDisabled: true, // 选择特殊医院时禁用项目选择
      itemNameList: [], // 选择特殊医院的项目列表
      isCenter: true,
      pickHospitalList: [],
      pickOfficeList: [],
      pickDoctorList: [],
      pickHospitalItemList: [], //医院项目组列表
      pickInstitutionList: [], // 医检机构
      pickInsOfficeList: [],
      pickSyUserList: [],
      pickSampleTypeList: [],
      itemContentList: [], //医院项目内容列表

      disabled: false,
      disabledBtn: false,
      userRole: '',
      dialogImageUrl: '',
      dialogImageAlt: '',
      dialogVisible: false,
      dialogSameTipVisible: false, //3天内录有同医院同名提醒
      continueOrCancel: 0, //0 表示没有操作，1表示取消，2表示确认
      dialogSameTipTitle: '',
      dialogSameTipContent: '',
      insCodeHide: true,
      dialogOfficeFormVisible: false,
      dialogDoctorFormVisible: false,
      addOfficeForm: {
        hospitalId: '',
        officeName: '',
      },
      addDoctorForm: {
        hospitalId: '',
        officeId: '',
        doctorName: '',
        doctorTitle: '',
      },
      reportForm: {
        codeFlag: 1,
        myReportCode: '',
        searchCode: '',
        patientName: '',
        patientSex: '',
        patientAge: '',
        patientMonth: '',
        patientDay: '',
        birthday: '',
        patientPhone: '',
        cardType: 1,
        patientCard: '',
        patientInfo: '',
        itemName: '',
        sampleTypeList: [],
        isRemind: '0',
        priority: '0',
        hospitalId: '',
        officeId: '',
        doctorId: '',
        hospitalItemIdList: [], //医院组合项目id
        institutionId: '',
        insOfficeId: '',
        insReportCode: '',
        reportState: '',
        syUserId: '',
        syUserIdTwo: '', //二级收样员
        syUserIdList: [], // 三级及其后续收样员
        reportBeginTime: '',
        remark: '',
        reportImageList: [],
        insItemIdList: [],
        originInfo: '',
      },
      sampleTypeData: {
        sampleTypeOne: '',
        sampleTypeList: [],
      },
      sameReportList: [], // 相同平台/医检条码号的旧报告单列表
      pickerBeginDateBefore: {
        disabledDate(time) {
          //return time.getTime() > Date.now();
        },
      },
      timeDefaultShow: '',
      roleRules: {
        institutionId: [
          {
            required: true,
            message: '请选择医检机构',
            trigger: 'change',
          },
        ],
        itemName: [
          {
            required: true,
            message: '请输入或选择项目名称',
            trigger: 'blur',
          },
        ],
        /*sampleTypeOne:[
          {
            required: true,
            message: "请选择检验样本",
            trigger:"blur"
          }
        ],*/
        patientName: [
          {
            required: true,
            message: '请输入患者姓名',
            trigger: 'blur',
          },
        ],
        hospitalId: [
          {
            required: true,
            message: '请选择医院',
            trigger: 'change',
          },
        ],
        cardType: [
          {
            required: true,
            message: '请选择证件类型',
            trigger: 'change',
          },
        ],
        patientAge: [
          {
            pattern: /^([1-9]|[1-9]\d|1\d{2}|200)$/,
            message: '年龄输入错误',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  components: {
    Map,
    RichEditor,
    SameReportCheck,
  },
  beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = true;
    next();
  },
  computed: {
    showTimeTip() {
      const { reportBeginTime } = this.reportForm;
      if (reportBeginTime && new Date(reportBeginTime).getTime() < Date.now()) return true;
      return false;
    },
  },
  watch: {
    dialogSameTipVisible(value) {
      // 如果为2表示确认
      if (!value && this.continueOrCancel != 2) {
        this.continueOrCancel = 1;
      }
    },
    'reportForm.hospitalItemIdList': {
      async handler(val) {
        if (val && val.length) {
          const arr = this.pickHospitalItemList.filter((item) => val.some((item2) => item2 == item.value));
          this.reportForm.itemName = arr.map((item) => item.label).toString();
          // 获取项目数据
          arr.forEach((item) => (item.sampleId = ''));
          this.itemContentList = arr;
        } else {
          this.itemContentList = [];
        }
      },
    },
  },
  methods: {
    ...mapGetters({
      openTabs: 'getOpenTabs',
    }),
    ...mapActions({
      setOpenTabs: 'setOpenTabs',
      setActiveIndexPath: 'setActiveIndexPath',
      setDeleteTabs: 'setDeleteTabs',
      replaceOpenTab: 'replaceOpenTab',
    }),
    init() {
      this.$Utils.clearData(this.reportForm);
      this.reportForm.codeFlag = 1;
      this.reportForm.cardType = 1;
      this.userInfo = getStorage(stn.USER_INFO);
      if (this.userInfo) {
        this.userRole = this.userInfo.userRole;
      }
      this.listHospital();
      this.listSyUser();
    },
    // 通过出生日期计算出年龄
    getAgeByBirthday(birthday) {
      if (birthday) {
        birthday = birthday.split('-');
        let date = new Date();
        let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
        let age = today.map((val, index) => {
          return val - birthday[index];
        });
        if (age[2] < 0) {
          let lastMonth = new Date(today[0], today[1], 0);
          age[1]--;
          age[2] += lastMonth.getDate();
        }
        if (age[1] < 0) {
          age[0]--;
          age[1] += 12;
        }
        this.reportForm.patientAge = age[0];
      } else {
        this.reportForm.patientAge = '';
      }
    },

    async checkInsCodeIsExist() {
      const { insReportCode, institutionId } = this.reportForm;
      if (insReportCode) {
        this.insCodeHide = true;
        if (!institutionId) return this.$message.error('请选择医检机构');
        let cond = {
          institutionId,
          insReportCode,
        };
        try {
          const { data } = await ReportApi.getReportCount(cond);
          data && (this.insCodeHide = false);
        } catch (err) {
          this.insCodeHide = true;
        }
      }
    },
    // 医检列表
    async listInstitution() {
      this.loadingIns = true;
      const { hospitalItemIdList, hospitalId } = this.reportForm;
      // 判断医院项目是否存在如果存在那么就
      try {
        if (hospitalItemIdList.length > 0) {
          const { data } = await InstitutionApi.listInsByHosItemId({ hosItemIds: hospitalItemIdList + '' });
          setTimeout(() => {
            this.loadingIns = false;
            this.pickInstitutionList = (data || []).map((item) => {
              return {
                value: item.institutionId,
                label: item.institutionName,
              };
            });
          }, 200);
        } else {
          if (!hospitalId) return (this.pickInstitutionList = []);
          const { data } = InstitutionApi.getInsByHos({ hospitalId });
          setTimeout(() => {
            this.loadingIns = false;
            this.pickInstitutionList = (data || []).map((item) => {
              return {
                value: item.institutionId,
                label: item.institutionName,
              };
            });
          }, 200);
        }
      } catch (err) {
        this.pickInstitutionList = [];
      }
    },
    // 医检改变
    async institutionChange() {
      this.pickInsOfficeList = [];
      this.pickSampleTypeList = [];
      this.reportForm.insOfficeId = '';
      this.itemContentList.forEach((item) => (item.sampleId = ''));
      const { institutionId } = this.reportForm;
      if (!institutionId) return;
      let res = await OfficeApi.getOfficeNames({ institutionId }).then((res) => {
        setTimeout(() => {
          this.pickInsOfficeList = (res.data || []).map((item) => {
            return {
              value: item.officeId,
              label: item.officeName,
            };
          });
        }, 200);
      });

      try {
        let res2 = await InstitutionApi.insSampleTypes({ institutionId });
        setTimeout(() => {
          this.pickSampleTypeList = (res2.data || []).map((item) => {
            return {
              value: item.insSampleCode,
              label: item.insSampleName,
            };
          });
        }, 200);
      } catch (err) {
        this.pickSampleTypeList = [];
      }

      // 97/100 分别表示 重庆两家机构  101：珠海九龙
      // if (
      //   _this.reportForm.institutionId == 97 ||
      //   _this.reportForm.institutionId == 100 ||
      //   _this.reportForm.institutionId == 112 ||
      //   _this.reportForm.institutionId == 124
      // ) {
      //   InstitutionItemApi.listInsItemNameAndGroup(cond)
      //     .then(res => {
      //       setTimeout(() => {
      //         this.itemNameList = res.data.map(item => {
      //           return {
      //             value: item.itemId,
      //             label: item.itemName + "-" + item.itemGroup
      //           };
      //         });
      //       }, 200);
      //     })
      //     .catch(error => {
      //       _this.itemNameList = [];
      //       console.error(error);
      //     });
      //     this.itemDisabled = false;
      //     // this.isForbidItemName = false
      //     _this.reportForm.itemName = ""
      //     _this.reportForm.insItemIdList = []
      //     // 当切换到医检项目的时候，如果医院项目存在要清空医院名称医院项目还有项目名称这些数据
      //     if(_this.reportForm.hospitalItemIdList.length>0){
      //         _this.reportForm.hospitalId = "";

      //         _this.reportForm.hospitalItemIdList = []
      //         _this.pickHospitalItemList = []

      //     }

      // }else{
      //    _this.itemNameList = []
      //   this.itemDisabled = true;
      // }
    },
    // 医检项目改变
    // itemListChange(value) {
    //   let _this = this;
    //   // 首先遍历每一个value值 在用每一个value值去找对应的label
    //   if (value != undefined || value.length >= 0) {
    //     var newList = [];
    //     value.forEach(item => {
    //       let choseValue = item;
    //       var choseList = _this.itemNameList.find(item => {
    //         return item.value == choseValue;
    //       });
    //       newList.push(choseList.label);
    //     });
    //     _this.reportForm.itemName = newList.join("，");
    //     // 珠海可允许一个条码号绑定不同类型的项目，一个条码号可以扫多次
    //     if (_this.reportForm.institutionId == 112) {
    //       return;
    //     }

    //     // 筛选出相同科室的项目
    //     if (value.length == 0 || value.length == 1) {
    //       let cond = {
    //         institutionId: _this.reportForm.institutionId
    //       };
    //       if (value.length == 1) {
    //         cond.itemId = value[0];
    //       }
    //       InstitutionItemApi.listInsItemNameAndGroup(cond)
    //         .then(res => {
    //           setTimeout(() => {
    //             _this.itemNameList = res.data.map(item => {
    //               return {
    //                 value: item.itemId,
    //                 label: item.itemName + "-" + item.itemGroup
    //               };
    //             });
    //           }, 200);
    //         })
    //         .catch(error => {
    //           _this.itemNameList = [];
    //           console.error(error);
    //         });
    //     }

    //   }
    // },
    async listHospital() {
      this.loadingIns = true;
      const { data } = await HospitalApi.getHospitalNameList({ hospitalType: 1 });
      this.loadingIns = false;
      this.pickHospitalList = (data || []).map((item) => {
        return {
          value: item.hospitalId,
          label: item.hospitalName,
        };
      });
    },
    async hospitalChange() {
      const { reportForm } = this;
      this.pickOfficeList = [];
      reportForm.officeId = '';
      this.pickDoctorList = [];
      reportForm.doctorId = '';
      this.pickInstitutionList = [];
      reportForm.institutionId = '';
      // _this.reportForm.syUserId = "";
      this.pickHospitalItemList = [];
      reportForm.hospitalItemIdList = [];
      reportForm.itemName = '';
      const { hospitalId } = reportForm;
      if (!hospitalId) return this.$message.error('请先选择医院');
      let res = await OfficeApi.getOfficeNames({ hospitalId });
      setTimeout(() => {
        this.pickOfficeList = (res.data || []).map((item) => ({
          value: item.officeId,
          label: item.officeName,
        }));
      }, 200);

      // 获取医院项目列表
      let res2 = await HospitalItemApi.listHospitalItemsName({ hospitalId });
      setTimeout(() => {
        this.pickHospitalItemList = (res2.data || []).map((item) => ({
          ...item,
          value: item.itemId,
          label: item.itemName,
        }));
      }, 200);
    },
    async officeChange() {
      const { hospitalId, officeId } = this.reportForm;
      this.pickDoctorList = [];
      this.reportForm.doctorId = '';
      if (!hospitalId) return this.$message.error('请先选择医院');
      if (!officeId) return this.$message.error('请先选择科室');
      const { data } = await DoctorApi.getDoctorNames({ hospitalId, officeId });
      setTimeout(() => {
        this.pickDoctorList = (data || []).map((item) => ({
          value: item.doctorId,
          label: item.doctorName,
        }));
      }, 200);
    },
    // 医院项目改变
    hospitalItemChange() {
      this.pickInstitutionList = [];
      this.reportForm.institutionId = '';
      this.reportForm.itemName = '';
    },
    // 获取用户列表
    listSyUser() {
      let _this = this;
      AuthApi.listAdminByRole({
        roleId: 4,
      }).then((res) => {
        setTimeout(() => {
          this.pickSyUserList = res.data.map((item) => {
            return {
              value: item.userId,
              label: item.userName,
            };
          });
        }, 200);
      });
    },
    // 无限增加次级收样员
    addSubclass() {
      if (!this.reportForm.syUserId) {
        this.$message.error('请选择一级收样员');
        return;
      }
      if (!this.reportForm.syUserIdTwo) {
        this.$message.error('请选择二级收样员');
        return;
      }
      let data = { userId: null };
      this.reportForm.syUserIdList.push(data);
    },
    // 删除次级收样员
    deleteSubclass(index) {
      this.reportForm.syUserIdList.splice(index, 1);
    },
    // 显示多级收样员label
    changSyUserLabel(index) {
      let result = this.$Utils.numberToChinese(index);
      return result + '级收样员';
    },
    addSubSampleType() {
      let data = { id: null };
      this.sampleTypeData.sampleTypeList.push(data);
    },
    deleteSubSampleType(index) {
      this.sampleTypeData.sampleTypeList.splice(index, 1);
    },
    addOffice() {
      let _this = this;
      if (_this.reportForm.hospitalId == '' || _this.reportForm.hospitalId == null) {
        _this.$message.error('请先选择医院');
        return;
      }
      this.dialogOfficeFormVisible = true;
      _this.addOfficeForm.hospitalId = _this.reportForm.hospitalId;
    },
    dismissOffice() {
      this.dialogOfficeFormVisible = false;
      this.addOfficeForm.hospitalId = '';
      this.addOfficeForm.officeName = '';
    },
    commitOffice() {
      let _this = this;
      var str = _this.addOfficeForm.officeName.replace(/(^\s*)|(\s*$)/g, ''); //去除空格
      if (str == '' || str == undefined || str == null) {
        _this.$message.error('请输入科室名称');
        return;
      }
      OfficeApi.addOffice(this.addOfficeForm).then((res) => {
        _this.dialogOfficeFormVisible = false;
        this.$Utils.notifySuccess();
        this.hospitalChange();
      });
    },
    addDoctor() {
      let _this = this;
      if (_this.reportForm.hospitalId == '' || _this.reportForm.hospitalId == null) {
        _this.$message.error('请先选择医院');
        return;
      }
      if (_this.reportForm.officeId == '' || _this.reportForm.officeId == null) {
        _this.$message.error('请先选择科室');
        return;
      }
      this.dialogDoctorFormVisible = true;
      _this.addDoctorForm.hospitalId = _this.reportForm.hospitalId;
      _this.addDoctorForm.officeId = _this.reportForm.officeId;
    },
    dismissDoctor() {
      this.dialogDoctorFormVisible = false;
      this.addDoctorForm.hospitalId = '';
      this.addDoctorForm.officeId = '';
      this.addDoctorForm.doctorName = '';
      this.addDoctorForm.doctorTitle = '';
    },
    commitDoctor() {
      let _this = this;
      var str = _this.addDoctorForm.doctorName.replace(/(^\s*)|(\s*$)/g, ''); //去除空格
      if (str == '' || str == undefined || str == null) {
        _this.$message.error('请输入医生姓名');
        return;
      }
      var strTitle = _this.addDoctorForm.doctorTitle.replace(/(^\s*)|(\s*$)/g, ''); //去除空格
      if (strTitle == '' || strTitle == undefined || strTitle == null) {
        _this.addDoctorForm.doctorTitle = '无';
        /*this.$notify.error({
          title: '错误',
          message: '请输入医生职称'
        });
        return;*/
      }
      DoctorApi.addDoctor(_this.addDoctorForm).then((res) => {
        _this.dialogDoctorFormVisible = false;
        _this.$Utils.notifySuccess();
        _this.officeChange();
      });
    },
    // 新增过程中的表单校验

    // 当电话号码以及身份证号码输入框发生改变 且不为空时 校验该内容的合法性
    phoneChange(val) {
      if (!this.$Utils.isEmptyObject(val)) {
        if (!this.$Utils.isMobile(val)) {
          this.$Utils.messageError('电话号码格式错误');
          this.disabledBtn = true;
        } else {
          this.disabledBtn = false;
        }
      } else {
        this.disabledBtn = false;
      }
    },
    clickCardType(val) {
      if (val == 9) {
        this.disabledBtn = false;
      }
    },
    cardChange(val) {
      if (!this.$Utils.isEmptyObject(val)) {
        if (!this.$Utils.isCardNo(val) && this.reportForm.cardType == 1) {
          this.$Utils.messageError('身份证号码格式错误');
          this.disabledBtn = true;
        } else {
          this.disabledBtn = false;
        }
      } else {
        this.disabledBtn = false;
      }
    },

    // 获取文本
    getHtmlText(val) {
      this.reportForm.originInfo = val;
    },
    // 继续确认
    continueConfirm() {
      this.continueOrCancel = 2; //确认后值为2
      this.dialogSameTipVisible = false;
    },
    // 是否继续
    whetherContinue(dialogSameTipMessgae, dialogSameTipTitle) {
      this.dialogSameTipVisible = true;
      this.continueOrCancel = 0; //初始话未0表示未操作
      (this.dialogSameTipTitle = dialogSameTipTitle), (this.dialogSameTipContent = dialogSameTipMessgae);
      return new Promise((resolve, reject) => {
        console.log('定时任务');
        let timer = setInterval(() => {
          // 只有continueOrCancel是2的时候才是继续操作，是1表示取消，开始为0表示没有操作
          if (this.continueOrCancel == 2) {
            resolve();
          } else if (this.continueOrCancel == 1) {
            reject();
          }
          if (!this.dialogSameTipVisible) {
            clearInterval(timer);
          }
        }, 1000);
      });
    },
    // 前端校验
    sureReportClick() {
      this.$refs.reportForm.validate((valid) => {
        if (valid) {
          // 收样员判断
          if (!this.reportForm.syUserId && this.reportForm.syUserIdTwo) {
            this.$message.error('请选择一级收样员');
            return;
          }
          let syList = this.reportForm.syUserIdList;
          if (syList && syList.length > 0) {
            if (!this.reportForm.syUserId) {
              this.$message.error('请选择一级收样员');
              return;
            }
            if (!this.reportForm.syUserIdTwo) {
              this.$message.error('请选择二级收样员');
              return;
            }
            let syListTwo = syList.filter((item) => {
              return item.userId != null;
            });
            if (syList.length !== syListTwo.length) {
              this.$message.error('请选择多级收样员');
              return;
            }
          }
          // 如果是广东祈福医院那么患者身份证或者性别、年龄、出生日期必须选择一个填写完整
          if (this.reportForm.institutionId == 124) {
            if ((!this.reportForm.patientSex || !this.reportForm.birthday || !this.reportForm.patientAge) && !this.reportForm.patientCard) {
              this.$message.error('请输入完整性别、年龄、出生日期或者输入身份证');
              return;
            }
          }

          // 如果是医检项目那么必须填写项目
          // if(!this.itemDisabled){
          //   if(this.reportForm.insItemIdList.length<1){
          //     this.$message.error("请选择医检项目")
          //     return
          //   }
          // }
          this.$confirm(this.showTimeTip ? '所选时间为今天之前，请注意提交申请通过后再录入！' : message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
            // 判断是否同号
            this.addBeforeCheck();
            // add
            //this.addReport()
          });
        }
      });
    },
    // 后端校验
    async addBeforeCheck() {
      let reportFormData = {
        isAdd: true,
        myReportCode: this.reportForm.myReportCode,
        itemName: this.reportForm.itemName,
        hospitalId: this.reportForm.hospitalId,
        officeId: this.reportForm.officeId,
        doctorId: this.reportForm.doctorId,
        hosItemIds: this.reportForm.hospitalItemIdList, //医院项目id
        institutionId: this.reportForm.institutionId,
        insReportCode: this.reportForm.insReportCode,
        patientName: this.reportForm.patientName,
        patientSex: this.reportForm.patientSex,
        patientAge: this.reportForm.patientAge,
        patientMonth: this.reportForm.patientMonth,
        patientDay: this.reportForm.patientDay,
      };
      const { data } = await ReportApi.checkReportAdd(reportFormData);
      // remindType提醒类型（1.3天内录有同医院同名提醒）
      if (data.remindType == 1) {
        try {
          await this.whetherContinue(data.remindMsg, message.MSG_CONFIRM_IS_CONTINUE);
          if (data.reportList && data.reportList.length > 0) {
            this.sameReportList = data.reportList;
            this.$refs.sameReportCheck.handleCreate();
          } else {
            this.addReport();
          }
        } catch (err) {
          this.$message.info('已取消');
        }
      } else {
        if (data.reportList && data.reportList.length > 0) {
          this.sameReportList = data.reportList;
          this.$refs.sameReportCheck.handleCreate();
        } else {
          this.addReport();
        }
      }
    },
    addReportSure() {
      this.reportForm.codeFlag = 2;
      this.addReport();
    },
    async addReport() {
      const res = await ReportApi.checkoutLicense({ hospitalId: this.reportForm.hospitalId, officeId: this.reportForm.officeId });
      if (!res.data) {
        await this.$alert('该医院没有营业执照', '提示', {
          type: 'warning',
          showClose: false,
        });
      }

      // 项目样本类型
      // let sampleTypeList = [];
      // if (!_this.$Utils.isNull(_this.sampleTypeData.sampleTypeOne)) {
      //   sampleTypeList.push(_this.sampleTypeData.sampleTypeOne);
      // }
      // if (!_this.$Utils.isNull(_this.sampleTypeData.sampleTypeList)) {
      //   if (_this.sampleTypeData.sampleTypeList.length > 0) {
      //     _this.sampleTypeData.sampleTypeList.forEach(a => {
      //       sampleTypeList.push(a.id);
      //     });
      //   }
      // }
      let reportFormData = {
        codeFlag: this.reportForm.codeFlag,
        myReportCode: this.reportForm.myReportCode,
        searchCode: this.reportForm.searchCode,
        patientName: this.reportForm.patientName,
        patientSex: this.reportForm.patientSex,
        birthday: this.reportForm.birthday,
        patientAge: this.reportForm.patientAge,
        patientMonth: this.reportForm.patientMonth,
        patientDay: this.reportForm.patientDay,
        patientPhone: this.reportForm.patientPhone,
        cardType: this.reportForm.cardType,
        patientCard: this.reportForm.patientCard,
        patientInfo: this.reportForm.patientInfo,
        remark: this.reportForm.remark,
        itemName: this.reportForm.itemName,
        insItemIdList: this.reportForm.insItemIdList,

        sampleCodeList: this.itemContentList.map((item) => item.sampleId || ''),

        isRemind: parseInt(this.reportForm.isRemind),
        priority: parseInt(this.reportForm.priority),
        hospitalId: this.reportForm.hospitalId,
        officeId: this.reportForm.officeId,
        doctorId: this.reportForm.doctorId,
        hosItemIds: this.reportForm.hospitalItemIdList, //医院项目id
        institutionId: this.reportForm.institutionId,
        insOfficeId: this.reportForm.insOfficeId,
        insReportCode: this.reportForm.insReportCode,
        syUserId: this.reportForm.syUserId,
        syUserIdTwo: this.reportForm.syUserIdTwo, //二级收样员
        syUserIdList: this.reportForm.syUserIdList, // 第三级收样员开始的数组对象
        reportState: this.reportForm.reportState,
        reportBeginTime: this.reportForm.reportBeginTime,
        reportImageList: this.reportForm.reportImageList,
        originInfo: this.reportForm.originInfo,
        reportSource: 2,
      };
      ReportApi.addReport(reportFormData).then((data) => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    handleRemove(file, fileList) {
      if (file.response) {
        const url = file.response.url;
        this.reportForm.reportImageList.splice(this.reportForm.reportImageList.indexOf(url), 1);
      }
    },
    handlePictureCardPreview(file) {
      //this.dialogImageUrl = file.url
      this.dialogImageUrl = '/static/img/pdfdefault.jpg';
      this.dialogImageAlt = file.name;
      this.dialogVisible = true;
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      //this.$router.go(-1);
      this.$router.push({ path: '/report/reportManagement' });
    },
  },
  mounted() {
    this.timeDefaultShow = new Date();
    this.reportForm.patientSex = 1;
    this.reportForm.cardType = 1;
    this.init();
  },
};
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope></style>
<style scoped>
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/ input[type='number'] {
  -moz-appearance: textfield;
}
.main_box {
  position: absolute;
  width: calc(100% - 50px);
  height: calc(100vh - 113px);
  overflow: auto;
  border: 1px solid #e6e6e6;
  margin: 10px;
}
.add_wrap {
  border: none;
  padding-top: 10px;
}
</style>
